package gov.pbc.nn.core.bdf.authoritydelegation.view.select;

import gov.pbc.nn.core.bdf.authoritydelegation.AuthoritydelegationHibernateDao;
import gov.pbc.nn.core.bdf.authoritydelegation.service.IAuthoritydelegationService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;

import com.bstek.bdf2.core.business.IDept;
import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.service.IDeptService;
import com.bstek.dorado.annotation.DataProvider;

/**
 * @author lucas.yue@bstek.com
 * 
 *         2013-4-20 下午11:26:24
 */
public class CopyOfDeptSelect extends AuthoritydelegationHibernateDao {
	private IDeptService deptService;

	@DataProvider
	public Collection<Map<String, Object>> loadDepts(String parentId)
			throws Exception {
		IUser user = ContextHolder.getLoginUser();
		if (user == null) {
			throw new RuntimeException("Please login first");
		}
		String companyId = user.getCompanyId();
		if (StringUtils.isNotEmpty(getFixedCompanyId())) {
			companyId = getFixedCompanyId();
		}
		if (user.isAdministrator()) {
			deptService = ContextHolder.getBean(IDeptService.BEAN_ID);
			List<IDept> topDeptList = deptService.loadDeptsByParentId(null,
					companyId);
			List<Map<String, Object>> depts = new ArrayList<Map<String, Object>>();
			for (IDept dept : topDeptList) {
				Map<String, Object> deptMap = this.toMap(dept);
				this.getChildren(deptMap, companyId);
				depts.add(deptMap);
			}
			return depts;
		} else {
			IAuthoritydelegationService ad = ContextHolder
					.getBean(IAuthoritydelegationService.BEAN_ID_);
//			return ad.findControllableDepts(parentId, user.getUsername());
			return null;
		}
	}

	private void getChildren(Map<String, Object> dept, String companyId)
			throws Exception {
		List<IDept> depts = deptService.loadDeptsByParentId(
				(String) dept.get("id"), companyId);
		List<Map<String, Object>> children = new ArrayList<Map<String, Object>>();
		for (IDept d : depts) {
			children.add(this.toMap(d));
		}
		dept.put("children", children);

		for (Map<String, Object> d : children) {
			this.getChildren(d, companyId);
		}
	}

	@SuppressWarnings("unchecked")
	private Map<String, Object> toMap(IDept dept) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(dept);
		return mapper.readValue(json, Map.class);
	}

}
